package net.dfrz.oa.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.dfrz.oa.dao.repository.OfficeRepository;
import net.dfrz.oa.pojo.Office;
import net.dfrz.oa.service.OfficeService;
import net.dfrz.oa.utils.PageBean;

@Service
public class OfficeServiceImpl implements OfficeService{

	@Autowired
	private OfficeRepository officeRepository;
	
	@Transactional(readOnly=true)
	public List<Office> getAll(){
		return officeRepository.findAll();
	}

	/**
	 * 无条件分页查询
	 */
	@Override
	@Transactional(readOnly=true)
	public Page<Office> queryPageList(PageBean<Office> pageList) {
		PageRequest pageable = new PageRequest(pageList.getPageNo()- 1, pageList.getPageSize());
		return officeRepository.findAll(pageable);
	}

	/**
	 * 带查询条件的分页查询
	 */
	@Override
	@Transactional(readOnly=true)
	public Page<Office> queryPageList(PageBean<Office> pageList, String query) {
		PageRequest pageable = new PageRequest(pageList.getPageNo()- 1, pageList.getPageSize());
		//将查询条件设置静态变量给匿名类传值
		final String name = query;
		//通常使用 Specification 的匿名内部类
		Specification<Office> specification = new Specification<Office>() {
		
			@Override
			public Predicate toPredicate(Root<Office> root,
					CriteriaQuery<?> cq, CriteriaBuilder cb) {
				Path path =root.get("name");
				Predicate predicate = cb.like(path, "%"+name+"%");
				return predicate;
			}
		};
		return officeRepository.findAll(specification, pageable);
	}
	
	/**
	 * 登记新购买的办公用品
	 */
	@Override
	@Transactional
	public void addOffice(Office office) {
		officeRepository.save(office);
	}

	/**
	 * 更新办公用品
	 */
	@Override
	@Transactional
	public void updateOffice(Office office) {
		officeRepository.updateOffice(office.getId(),office.getName(),office.getCount(),office.getUnit());
	}

	/**
	 * 根据id查询办公用品
	 */
	@Override
	@Transactional(readOnly=true)
	public Office getOfficeById(Integer id) {
		return officeRepository.findOne(id);
	}
}
